package com.jiong.ad.controller;

import com.jiong.ad.entity.Advertisement;
import com.jiong.ad.service.IAdvertisementService;
import com.jiong.ad.vo.AdVO;
import com.jiong.common.PageResult;
import com.jiong.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 广告表 前端控制器
 * </p>
 *
 * @author jiong
 * @since 2025-01-16
 */
@RestController
@RequestMapping("/advertisement")
public class AdvertisementController {
    @Autowired
    IAdvertisementService advertisementService;

    @GetMapping("/list")
    public R list() {
        return R.ok().data("list", advertisementService.list());
    }

    @GetMapping("/findByPage")
    public R findByPage(@RequestParam("page") Integer page,
                        @RequestParam("pageSize") Integer pageSize) {
        PageResult<Advertisement> pageResult = advertisementService.findByPage(page,pageSize);
        return R.ok().data("pageResult",pageResult);
    }

    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page,
                    @PathVariable("pageSize") Integer pageSize,
                    @RequestBody(required = false) AdVO adVO) {
        PageResult<Advertisement> pageResult = advertisementService.search(page, pageSize, adVO);
        return R.ok().data("pageResult", pageResult);
    }

    @PostMapping("/add")
    public R addAdvertisement(@RequestBody Advertisement advertisement) {
        boolean isAdded = advertisementService.add(advertisement);
        if (isAdded) {
            return R.ok().message("广告添加成功！");
        } else {
            return R.error().message("广告添加失败！");
        }
    }

    @PutMapping("/update")
    public R updateStudent(@RequestBody Advertisement advertisement) {
        boolean isUpdated = advertisementService.updateById(advertisement);
        if ( isUpdated ) {
            return R.ok().message("修改广告信息成功！");
        } else {
            return R.error().message("修改广告信息失败！");
        }
    }

    @DeleteMapping("/delete/{adsIds}")
    public R deleteStudents(@PathVariable("adsIds") String adsIds) {
        String[] idArray = adsIds.split(",");
        List<String> adIdList = Arrays.asList(idArray);
        boolean isDeleted = advertisementService.removeByIds(adIdList);
        if (isDeleted) {
            return R.ok().message("删除音乐成功！");
        } else {
            return R.error().message("删除音乐失败！");
        }
    }
}
